package com.rest.demo.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * @author Administrator
 * @decription 线程间通信
 * @Date 2018-01-31 16:52
 */
public class NotifyDemo {
    
    public static void main(String[] args) {
        Task task = new Task();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                task.sub(i);
            }
        }).start();

        for (int i = 0; i < 50; i++) {
            task.main(i);
        }
    }
}
class Task {

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    private static boolean bShouldSub = true;

    public void sub(int i) {
        lock.lock();
        try {
            while(!bShouldSub) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            IntStream.range(0,10).forEach(j -> System.out.println("sub thread sequence of " + j + ", loop of " + i));
            bShouldSub = false;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public void main(int i) {
        lock.lock();
        try {
            while (bShouldSub) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            IntStream.range(0,5).forEach(j -> System.out.println("main thread sequence of " + j + ", loop of " + i));
            bShouldSub = true;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}
